package com.fans.admin.generator.controller;


import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fans.admin.generator.entity.TableInfo;
import com.fans.admin.generator.service.IGenService;
import com.fans.common.base.BaseController;
import com.fans.common.utils.Convert;
import com.fans.common.utils.FansResp;
import com.fans.common.vo.PageFactory;
import com.fans.common.vo.PageVo;

@RestController
@RequestMapping("/generator/gen")
public class GenController extends BaseController {

	@Autowired
	private IGenService genService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Object list(TableInfo tableInfo, PageVo pv, String condition, HttpServletResponse response) {
		pv.setSortField("create_time");
		pv.setSortOrder("desc");
		Page<TableInfo> page = new PageFactory<TableInfo>().page(pv);
		List<TableInfo> result = genService.selectTableList(page, tableInfo);
		page.setRecords(result);
		return renderString(response, FansResp.successData(page));
	}
	
	/**
     * 生成代码
     */
	@RequestMapping(value = "/genCode/{tableName}", method = RequestMethod.POST)
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        byte[] data = genService.generatorCode(tableName);
        IOUtils.write(data, response.getOutputStream());
    }


	/**
	 * 批量生成代码
	 */
	@RequestMapping(value = "/batchGenCode", method = RequestMethod.POST)
	public void batchGenCode(HttpServletResponse response, @RequestBody JSONObject jsonParam)
			throws IOException {
		String[] tableNamesArr = Convert.toStrArray(jsonParam.getString("tableNames"));
		byte[] data = genService.generatorCode(tableNamesArr);
		IOUtils.write(data, response.getOutputStream());
	}
}